package coroutines.interceptor

import kotlin.coroutines.Continuation
import kotlin.coroutines.ContinuationInterceptor
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.startCoroutine

class ExceptionInterceptor : ContinuationInterceptor {
    companion object Key : CoroutineContext.Key<LogInterceptor>

    override val key = Key
    override fun <T> interceptContinuation(continuation: Continuation<T>): Continuation<T> {
        return object : Continuation<T> {
            override val context = continuation.context

            override fun resumeWith(result: Result<T>) {
                try {
                    println("ExceptionInterceptor run)")
                    continuation.resumeWith(result)
                } catch (e: Exception) {
                    if (e is CustomException) {
                        println("ExceptionInterceptor CustomException)")
                    } else {
                        println("ExceptionInterceptor other exception)")
                        throw  e
                    }
                }
            }
        }
    }
}

class CustomException : java.lang.Exception()

fun main() {
    suspend {
        println("正在测试拦截器")
//        delay(1000)
        println("还是在测试按揭器")
        "测试"
    }.startCoroutine(object : Continuation<Any?> {
        override val context: CoroutineContext = ExceptionInterceptor()

        override fun resumeWith(result: Result<Any?>) {
            println("Interceptor test resumeWith(${result.getOrNull()})")

            try {
                throw CustomException()
            } catch (e: java.lang.Exception) {
                println("Interceptor CustomException catched")
            }

            try {
                throw java.lang.Exception()
            } catch (e: java.lang.Exception) {
                println("Interceptor Exception catched")
            }
        }
    })
}

